import { Link, useNavigate } from "react-router-dom";
import styles from "./Login.module.scss";
import { UserAddOutlined } from "@ant-design/icons";
import { Button, Checkbox, Form, Input, message, Space } from "antd";
import Title from "antd/es/typography/Title";
import { MANAGE_INDEX_PATHNAME, REGISTER_PATHNAME } from "../router";
import { useEffect } from "react";
import { useRequest } from "ahooks";
import { loginService } from "../service/user";
import { setToken } from "../utils/user-token";
const USERNAME_KEY = "USERNAME";
const PASSWORD_KEY = "PASSWORD";
function rememberUser(username, password) {
  localStorage.setItem(USERNAME_KEY, username);
  localStorage.setItem(PASSWORD_KEY, password);
}
function deleteUserFromStorage() {
  localStorage.removeItem(USERNAME_KEY);
  localStorage.removeItem(PASSWORD_KEY);
}
function getUserInfoFormStorage() {
  const username = localStorage.getItem(USERNAME_KEY);
  const password = localStorage.getItem(PASSWORD_KEY);
  if (username && password) {
    return {
      username,
      password,
    };
  } else {
    return null;
  }
}
export default function Login() {
  const nav = useNavigate();
  const [form] = Form.useForm();
  useEffect(() => {
    const userInfo = getUserInfoFormStorage();
    if (userInfo) {
      form.setFieldsValue(userInfo);
    }
  });
  const { run, loading } = useRequest(
    async (values) => {
      const { username, password } = values;
      const data = await loginService(username, password);
      return data;
    },
    {
      manual: true,
      onSuccess(result) {
        const { token = "" } = result;
        setToken(token);
        message.success("登录成功");
        nav(MANAGE_INDEX_PATHNAME);
      },
    }
  );
  function onFinish(val: any) {
    const { username, password, remember } = val;
    run(val);
    if (username && password) {
      if (remember) {
        rememberUser(username, password);
      } else {
        deleteUserFromStorage();
      }
    }
  }
  return (
    <div className={styles.container}>
      <div>
        <Space>
          <Title level={2}>
            <UserAddOutlined />
          </Title>
          <Title level={2}>用户登录</Title>
        </Space>
      </div>
      <div>
        <Form
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          initialValues={{ remember: true }}
          form={form}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: "请输入用户名",
              },
              {
                type: "string",
                min: 5,
                max: 20,
                message: "字符长度在5-20之间",
              },
              {
                pattern: /^\w+$/,
                message: "只能是字母数字下划线",
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: "请输入密码",
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="remember"
            valuePropName="checked"
            wrapperCol={{ offset: 6 }}
          >
            <Checkbox>记住我</Checkbox>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                登录
              </Button>
              <Link to={REGISTER_PATHNAME}>注册新用户</Link>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
